<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model.trim="spu.spuName" placeholder="SPU名称" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model.trim="spu.tmId" placeholder="请选择品牌">
          <el-option v-for="item in trademarkList" :key="item.id" :label="item.tmName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input v-model.trim="spu.description" type="textarea" rows="4" placeholder="描述" />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="success"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select v-model="attrIdName" :placeholder="`还有${unSelect.length}未选择`">
          <!-- 拼接上ID和name并且绑定 -->
          <el-option v-for="item in unSelect" :key="item.id" :label="item.name" :value="`${item.id}:${item.name}`" />
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="unSelect.length===0" @click="addSale">添加销售属性</el-button>
        <el-table
          border
          style="width: 100%;margin:15px 0"
          :data="spu.spuSaleAttrList"
        >
          <template slot="empty">
            <el-empty description="空" />
          </template>
          <el-table-column
            prop="prop"
            label="序号"
            width="80px"
            type="index"
          />
          <el-table-column
            prop="saleAttrName"
            label="属性名"
            width="150px"
          />
          <el-table-column
            prop="prop"
            label="属性值名称列表"
            width="width"
          >
            <template slot-scope="{row}">
              <div>
                <el-tag v-for="(item,i) in row.spuSaleAttrValueList" :key="item.id" :disable-transitions="true" closable style="margin:0 10px" @close="close(row,i)">
                  {{ item.saleAttrValueName }}
                </el-tag>
                <el-input
                  v-if="row.inputVisible"
                  ref="saveTagInput"
                  v-model.trim="row.saleAttrValueName"
                  class="input-new-tag"
                  size="small"
                  @blur="handleInputConfirm(row)"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150px"
          >
            <template slot-scope="{row,$index}">
              <div>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="del($index)" />
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      spu: {
        category3Id: 0,
        description: '',
        spuImageList: [],
        spuName: '',
        spuSaleAttrList: [],
        tmId: ''
      },
      spuId: '',
      trademarkList: [],
      spuImageList: [],
      saleAttrList: [],
      attrIdName: '' // 收集未选中的销售属性的ID
    }
  },
  computed: {
    parent() {
      return this.$parent.$parent
    },
    unSelect() {
      const res = this.saleAttrList.filter(item => {
        // 在数组中过滤掉返回值为false的值
        // every方法会返回一个布尔值
        // 出现重复的会返回false
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name !== item1.saleAttrName
        })
      })
      return res
    }
  },
  methods: {
    // 删除图片的时候
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.spuImageList = fileList
    },
    // 图片预览时的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传成功时的回调
    success(response, file, fileList) {
      this.spuImageList = fileList
    },
    cancel() {
      // 清理data中的值
      Object.assign(this._data, this.$options.data())
      this.parent.scene = 0
    },
    async getData(e) {
      this.spuId = e
      const res = await this.$api.spu.getSpuById(e)
      if (res.code === 200) {
        this.spu = res.data
      }
      // 获取品牌的信息
      const res2 = await this.$api.spu.getTrademarkList()
      if (res2.code === 200) {
        this.trademarkList = res2.data
      }
      // 获取spu图片数据
      const res3 = await this.$api.spu.getSkuById(e)
      if (res3.code === 200) {
        res3.data.forEach((item) => {
          this.spuImageList.push({ name: item.imgName, url: item.imgUrl })
        })
      }
      // 销售属性列表
      const res4 = await this.$api.spu.baseSaleAttrList()
      if (res4.code === 200) {
        this.saleAttrList = res4.data
      }
    },

    showInput(e) {
      this.$set(e, 'inputVisible', true)
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm(e) {
      // 不能为空
      if (e.saleAttrValueName === '' || e.saleAttrValueName === undefined) {
        this.$message.error('不能为空')
        this.$refs.saveTagInput.$refs.input.focus()
        return
      }
      // 不能重复(some来查询数组中是否含有当前值,如果出现重复的会返回true)
      const res = e.spuSaleAttrValueList.some(item => item.saleAttrValueName === e.saleAttrValueName)
      if (res === true) {
        this.$message.error('不能重复')
        return
      }
      const { saleAttrName, saleAttrValueName } = e
      const attrValue = { saleAttrName, saleAttrValueName, spuId: this.spuId, baseSaleAttrId: 1 }
      e.spuSaleAttrValueList.push(attrValue)
      // 已经是响应式数据所以就不需要使用set了
      e.inputVisible = false
    },
    // 添加新的销售属性
    addSale() {
      if (this.attrIdName === '') {
        this.$message.error('不能为空')
        return
      }
      // 分割解构出来
      const [baseSaleAttrId, saleAttrName] = this.attrIdName.split(':')
      const spuSaleAttrList = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(spuSaleAttrList)
      this.attrIdName = ''
    },
    // 关闭tag框
    close(row, i) {
      // 直接改原数组
      row.spuSaleAttrValueList.splice(i, 1)
    },
    // 删除索引值
    del(index) {
      this.spu.spuSaleAttrList.splice(index, 1)
    },
    // 保存
    async save() {
      // imgName
      // imgUrl
      //   spuId
      this.spu.spuImageList = this.spuImageList.map(item => {
        return {
          imageName: item.name,
          imageUrl: item.response !== undefined ? (item.response && item.response.data) : item.url
        }
      })
      const res = await this.$api.spu.saveSpuInfo(this.spu)
      if (res.code === 200) {
        this.$message({ type: 'success', message: '成功' })
        this.parent.page = 1
        this.parent.scene = 0
        // 使用this.$options.data()获取到起始状态,然后赋值给data覆盖
        Object.assign(this._data, this.$options.data())
        this.parent.getData()
      }
    },
    // 获取平台销售属性 销售属性列表
    async getSpuData() {
      this.spu.category3Id = this.parent.category3Id
      const res1 = await this.$api.spu.getTrademarkList()
      if (res1.code === 200) {
        this.trademarkList = res1.data
      }
      const res2 = await this.$api.spu.baseSaleAttrList()
      if (res2.code === 200) {
        this.saleAttrList = res2.data
      }
    }
  }
}
</script>

  <style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  </style>

